package com.appstore.controller;

import com.appstore.common.AjaxResult;
import com.appstore.domain.dto.LoginUserDTO;
import com.appstore.domain.entity.User;
import com.appstore.framework.web.service.SysLoginService;
import com.appstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.appstore.common.core.domain.model.LoginBody;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private SysLoginService loginService;

    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        return AjaxResult.success(userService.getById(id));
    }

    @PostMapping
    public AjaxResult register(@RequestBody User user) {
        if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getName()) || ObjectUtils.isEmpty(user.getPassword())) {
            return AjaxResult.error("用户名或密码不能为空");
        }
        //判断用户名是否存在
        User temp = userService.getByUserName(user.getName());
        if (!ObjectUtils.isEmpty(temp)) {
            return AjaxResult.error("该用户名已存在");
        }
        return AjaxResult.success("注册成功！", userService.register(user));
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginUserDTO loginUserDTO) {
//        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
//                loginBody.getUuid());
        User user = userService.getByUserName(loginUserDTO.getName());
        if(ObjectUtils.isEmpty(user)) {return AjaxResult.error("用户名或密码错误");}
        if(!user.getPassword().equals(loginUserDTO.getPassword())) {return AjaxResult.error("用户名或密码错误");}
        return AjaxResult.success("登陆成功",user.getId());
    }


}
